package com.reder.practice.common.listener;

import com.reder.practice.bean.Manager;
import com.reder.practice.bean.extend.ManagerExtend;
import com.reder.practice.common.enums.state.ManagerState;
import com.reder.practice.common.event.ManagerLoginEvent;
import com.reder.practice.common.util.SqlResultUtil;
import com.reder.practice.dao.ManagerDao;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

/**
 * 管理员登录事件监听器
 *
 * @author Fish
 * <p>Email: fishinlove@163.com</p>
 * <p>created by 2019/09/24 09:52:16</p>
 */
@Slf4j
@Component
public class ManagerLoginEventListener implements ApplicationListener<ManagerLoginEvent> {

    @Resource
    private ManagerDao managerDao = null;

    @Override
    public void onApplicationEvent(ManagerLoginEvent event) {

        // 记录日志
        logFor(event);

        // 更新数据
        updateLoginTime(event.getManager());
    }

    // 更新登录时间
    private void updateLoginTime(Manager manager) {
        Manager copyOfManager = new Manager();
        copyOfManager.setId(manager.getId());
        copyOfManager.setLastLoginTime(new Date());

        // 日志记录数据操作
        log.debug(SqlResultUtil.checkSqlResult(
                managerDao.updateByPrimaryKeySelective(copyOfManager),
                ManagerState.UPDATE_LOGIN_TIME_FAILED
        ).toString());
    }

    // 记录这次事件的发生
    private void logFor(ManagerLoginEvent event) {
        log.debug(
                String.format("管理员 %s 于 %s 进行登录！", event.getManager().getUserName(), event.getLoginTime())
        );
    }
}
